package com.formen.ndk;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

import android.app.Activity;
import android.app.Dialog;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentFilter.MalformedMimeTypeException;
import android.nfc.NdefMessage;
import android.nfc.NfcAdapter;
import android.nfc.tech.NfcF;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcelable;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

	public class NFCReceive extends Activity //implements CreateNdefMessageCallback
	{

		public static final String TAG = "NFCScanForegroundActivity";

	    public static final int REQ_CODE_PUSH = 1001;
	    public static final int SHOW_PUSH_CONFIRM = 2001;

	    public static ProgressDialog pDialog;
	    	
		private NfcAdapter mAdapter;	//어댑터 객체 선언
	    private PendingIntent mPendingIntent;
	    private IntentFilter[] mFilters;
	    private String[][] mTechLists;
	    private TextView mText;

	    ImageView imageView;
	    
		public static final int TYPE_TEXT = 1;
		public static final int TYPE_URI = 2;

        String [] profile;
		
	    public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);

	        mAdapter = NfcAdapter.getDefaultAdapter(this);	//어댑터 객체 참조        
	        
	        setContentView(R.layout.nfc_receive);

	        Log.d(TAG, "onCreate() called.");


	        mText = (TextView) findViewById(R.id.nfc_receive_tv1);
	        imageView = (ImageView)findViewById(R.id.nfc_image);
	        
	        if (mAdapter == null) {
	        	mText.setText("사용하기 전에 NFC를 활성화하세요.");
	        } else {
	        	mText.setText("NFC 태그를 스캔하세요.");
	        }

	        //mAdapter.setNdefPushMessageCallback(this,this);
	        
	        //인텐트 객체 생성 : 태그 데이터가 포함된 인텐트를 전달받았을 때 실행할 인텐트 객체 생성
	        Intent targetIntent = new Intent(this, NFCReceive.class);
	        targetIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
	        mPendingIntent = PendingIntent.getActivity(this, 0, targetIntent, 0);

	        
	      //인텐트 필터 객체 생성 : 인텐트를 전달받기 위한 인텐트 필터 객체 생성
	        IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);	
	        try {
	            ndef.addDataType("*/*");
	        } catch (MalformedMimeTypeException e) {
	            throw new RuntimeException("fail", e);
	        }

	        mFilters = new IntentFilter[] {
	                ndef,
	        };

	        mTechLists = new String[][] { new String[] { NfcF.class.getName() } };


	        Intent passedIntent = getIntent();
	        if (passedIntent != null) {
	        	String action = passedIntent.getAction();
	            if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)) {
	            	processTag(passedIntent);
	            }
	        }

	    }

	    public void onResume() {
	        super.onResume();

	        if (mAdapter != null) {
	        	//메소드 호출 : 화면이 보이기 전에 enableForegroundDispatch()메소드 호출
	        	mAdapter.enableForegroundDispatch(this, mPendingIntent, mFilters, mTechLists);	
	        }
	    }

	    public void onPause() {
	        super.onPause();

	        if (mAdapter != null) {
	        	//메소드 호출 : 화면이 중지될 때 enableForegroundDispatch()메소드 호출
	        	mAdapter.disableForegroundDispatch(this);
	        }
	    }

	    private void processTag(Intent passedIntent) {
	    	Log.d(TAG, "processTag() called.");

	        Parcelable[] rawMsgs = passedIntent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
	        if (rawMsgs == null) {
	        	Log.d(TAG, "NDEF is null.");
	        	return;
	        }

	    	mText.setText(rawMsgs.length + "개 태그 스캔됨");

	        NdefMessage[] msgs;
	        
	        if (rawMsgs != null) {
	            msgs = new NdefMessage[rawMsgs.length];
	            for (int i = 0; i < rawMsgs.length; i++) {
	                msgs[i] = (NdefMessage) rawMsgs[i];
	                showTag(msgs[i]);
	            }
	        }

	        showDialog(SHOW_PUSH_CONFIRM);
	    }


	    private int showTag(NdefMessage mMessage) {
	        List<ParsedRecord> records = NdefMessageParser.parse(mMessage);
	        final int size = records.size();
	        mText.append("\n");
	        for (int i = 0; i < size; i++) {
	            ParsedRecord record = records.get(i);

	            int recordType = record.getType();
	            String recordStr = "";
	            if (recordType == ParsedRecord.TYPE_TEXT) {
	            	//recordStr = "TEXT : " + ((TextRecord) record).getText() + "\n";
	            	recordStr = ((TextRecord) record).getText();
	            } else if (recordType == ParsedRecord.TYPE_URI) {
	            	recordStr = "URI : " + ((UriRecord) record).getUri().toString() + "\n";
	            }

	            Log.d(TAG, "record string : " + recordStr);
	            
	            profile = recordStr.split("@");
	            
	            mText.append(profile[0]);
	            mText.append("\n");
	            mText.append(profile[1]);
	            mText.append("\n");
	            mText.append(profile[2]);
	            mText.append("\n");
	            mText.append(profile[3]);
	            mText.append("\n");
	            mText.append(profile[4]);
	            mText.append("\n");
	            mText.append(profile[5]);
	            mText.invalidate();
	            /*
	            byte[] decodedString = Base64.decode(profile[3], Base64.DEFAULT);
	            Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length); 
	            imageView.setImageBitmap(decodedByte);
	           */
	            
	        }

	        return size;
	    }

	    public void onNewIntent(Intent passedIntent) {
	    	Log.d(TAG, "onNewIntent() called.");

	    	if (passedIntent != null) {
	        	processTag(passedIntent);
	        }
	    }


	    protected Dialog onCreateDialog(int id) {
	    	switch (id) {
				case SHOW_PUSH_CONFIRM:
					
					String filePath= Environment.getExternalStorageDirectory()
	                + "/E-Profile/user_information";
	        
					File dir = new File(filePath);
					
					if(!dir.exists())			dir.mkdir();				
					
					appendFile(filePath);
					Toast.makeText(getApplicationContext(), "Got Message!", Toast.LENGTH_SHORT).show();
					finish();
					break;

	    	}
	    	return null;
		}
	    
	    void appendFile(String path)
	    { 	
	    	path += "/user_log.txt";
	    	File dir = new File(path);
	    	BufferedWriter fw;
	    	String tmp = "";

	    	if(!dir.exists())	tmp += "아이디\t이름\t전화번호\t지역\t생년월일\t만난시간\t만난장소\n";
	    	
	    	if(!filterDuplicate(profile[0]) && !MainActivity.user_id.equals(profile[0]))
	    	{
	    	 try { 
	    		 	if(dir.exists())	fw = new BufferedWriter(new FileWriter(path,true)); 
	    		 	else				fw = new BufferedWriter(new FileWriter(path));
	    	      tmp = profile[0]+"\t"+profile[1]+"\t"+profile[2]+"\t"+profile[3]+"\t"+profile[4]+"\t"+profile[5];
	    		 fw.write(tmp);
	    	      fw.newLine(); 
	    	      fw.flush(); 
	    	      fw.close();   
	    	    } catch (FileNotFoundException e) { 
	    	        Toast.makeText(getApplicationContext(), "파일이 존재하지 않습니다.", Toast.LENGTH_SHORT).show();
	    	      } 
	    	      catch (IOException e) { 
	    	    	  Toast.makeText(getApplicationContext(), "파일 입력 예외 발생", Toast.LENGTH_SHORT).show();
	    	      } 
	    	}
	    }
	    
	    boolean filterDuplicate(String user)
		{
			String path = Environment.getExternalStorageDirectory()+"/E-Profile/user_information/user_log.txt";
	    	File dir = new File(path);
	    	BufferedReader br;
	    	String str;
	    	String [] strArr;
	    	boolean isDuplicate = false;
	    	
	    	 try {
	    		 	if(dir.exists())	br = new BufferedReader(new FileReader(dir)); 
	    		 	else				br = new BufferedReader(new FileReader(dir));
	    	
	    		 	while ((str = br.readLine()) != null) {
	    		        strArr = str.split("\t");
	    		        
	    		        if(strArr[0].equals(user))		
	    		        {
	    		        	isDuplicate = true;
	    		        	break;
	    		        }
	    		        
	    		 	}
	    		 	br.close();
	    	    } catch (FileNotFoundException e) { 
	    	    	Log.d("filterDuplicate", e.toString());
	    	      } 
	    	      catch (IOException e) { 
	    	    	  Log.d("filterDuplicate", e.toString());
	    	      } 
	    	 
	    	 /*
	    	  * 	return 0 : no problem
	    	  * 	return 1 : 
	    	  */
	    	 
	    	 return isDuplicate;
		}
/*
	    private NdefMessage createTagMessage(String msg, int type) {
	    	NdefRecord[] records = new NdefRecord[1];

	    	if (type == TYPE_TEXT) {
	    		records[0] = createTextRecord(msg, Locale.KOREAN, true);
	    	} else if (type == TYPE_URI){
	    		records[0] = createUriRecord(msg.getBytes());
	    	}

	    	NdefMessage mMessage = new NdefMessage(records);

	    	return mMessage;
	    }


	    private NdefRecord createTextRecord(String text, Locale locale, boolean encodeInUtf8) {
	        final byte[] langBytes = locale.getLanguage().getBytes(Charsets.US_ASCII);
	        final Charset utfEncoding = encodeInUtf8 ? Charsets.UTF_8 : Charset.forName("UTF-16");
	        final byte[] textBytes = text.getBytes(utfEncoding);
	        final int utfBit = encodeInUtf8 ? 0 : (1 << 7);
	        final char status = (char) (utfBit + langBytes.length);
	        final byte[] data = Bytes.concat(new byte[] {(byte) status}, langBytes, textBytes);
	        return new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT, new byte[0], data);
	    }

	    private NdefRecord createUriRecord(byte[] data) {
	        return new NdefRecord(NdefRecord.TNF_ABSOLUTE_URI, NdefRecord.RTD_URI, new byte[0], data);
	    }

*/


	}